import Axios from 'axios'
import {ElMessage} from "element-plus/es";
import router from "@/router";


const axios = Axios.create({
    withCredentials: true,
    baseURL: "/"
})

axios.interceptors.request.use((config) => {
    if (config.headers && localStorage.getItem("token")) {
        config.headers.Authorization = "Bearer " + localStorage.getItem("token")
    }
    return config
})


axios.interceptors.response.use((response) => {
    if (response.headers['refresh-token']) {
        localStorage.setItem("token", response.headers['refresh-token'])
    }
    if (!response.data) {
        ElMessage.error('服务器内部异常!')
    }
    if (response.status === 200) {
        if (response.data?.code !== 2000) {
            ElMessage.error(response.data.msg)
            return Promise.reject(response)
        }
    }
    return response;
}, (error) => {
    if (error.response.status === 401) {
        if (error.response.data?.code === 40001) {
            router.push('/').then((r: any) => console.log(r))
            const error = new Error();
            error.message = '登录已过期,请重新登录!'
            ElMessage.error('登录已过期,请重新登录!')
            return Promise.reject(error)
        }
    }
});

export default axios